import { Button, Layout, message, Modal, Select, SelectProps } from 'antd'
import Editor, { Monaco, useMonaco } from '@monaco-editor/react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { ExclamationCircleOutlined, ShareAltOutlined } from '@ant-design/icons'
import { Share } from '../../../wailsjs/go/main/ShareApp'
import './index.scss'
import stripAnsi from 'strip-ansi'
import { copyToClipboard, getHttpOrHttps } from '../../utils'

const { Content } = Layout

const shareOptions = [
  {
    value: '1',
    label: 'localcode.share',
  },
]

export default function ShareComponent() {
  const editorRef = useRef(null)
  const monaco = useMonaco()
  // const [languages, setLanguages] = useState<string[]>([])
  const [soptions, setOptions] = useState<SelectProps['options']>([])
  const [language, setLanguage] = useState('json')

  // share method
  const [shareMethod, setShareMethod] = useState('localcode.share')

  // 打开Modal
  const [modal, contextHolder] = Modal.useModal()

  // 获取分享后的结果
  const [shareResult, setShareResult] = useState('')

  const confirm = useCallback(() => {
    modal.confirm({
      title: 'Confirm',
      icon: <ExclamationCircleOutlined />,
      content: '确定要将内容分享给其他人吗? 当前分享方式: ' + shareMethod,
      okText: '确认',
      cancelText: '取消',
      centered: true,
      onOk() {
        if (editorRef.current) {
          const text = (editorRef.current as any).getValue()
          if (text === '') {
            message.warning('编辑器内容为空, 不能分享')
          } else {
            return new Promise<void>((resolve, reject) => {
              // 将编辑器中的内容转换为字节数组
              const encoder = new TextEncoder()
              const encodedText = encoder.encode(text)
              const encodedTextArray = Array.from(encodedText)
              // 调用go的Share方法
              Share(encodedTextArray, shareMethod)
                .then((res) => {
                  setShareResult(res)
                  message.success('分享成功, 即将打开分享的网页内容...')
                  const urls = getHttpOrHttps(res)
                  // 默认打开第一个网址
                  console.group(
                    '%cGrouped Output:',
                    'background-color: #e0005a ; color: #ffffff ; font-weight: bold ; padding: 4px ;',
                    urls,
                  )
                  window.open(urls![0])
                  resolve() // 接口成功后关闭对话框

                  copyToClipboard(urls![0])
                    .then(() => {
                      message.success('分享链接已复制到剪贴板', 5000)
                    })
                    .catch((err) => {
                      message.error('分享链接复制失败, 请重试')
                      console.error(err)
                    })
                })
                .catch((err) => {
                  console.error('err', err)
                  message.error('分享失败, 请重试')
                  reject(err) // 接口失败时通知错误
                })
            })
          }
        }
      },
    })
  }, [shareMethod, shareResult])

  // 获取所有的语言列表
  const getLangOptions = () => {
    if (monaco?.languages) {
      const _languages = monaco.languages.getLanguages().map((item) => item.id)
      // setLanguages(_languages)
      console.log('languages', _languages)

      // 构建options
      if (soptions) {
        setOptions((prevItems: any) => [
          ...prevItems,
          ..._languages.map((item) => ({ label: item, value: item })),
        ])
      }
    }
  }

  useEffect(() => {
    getLangOptions()
  }, [monaco])

  function handleEditorDidMount(editor: any, monaco: Monaco) {
    editorRef.current = editor
  }

  return (
    <>
      <Content className="body-area">
        <div className="share">
          <span className="share-title">
            <Button onClick={confirm} className="share-btn">
              分享
            </Button>
            &ensp;
            <ShareAltOutlined />
            <span className="share-title-text">&ensp;分享方式 : </span>
            <Select
              options={shareOptions}
              value={shareMethod}
              style={{ width: '100px' }}
              onSelect={(value) => {
                setShareMethod(value)
              }}
            />
            {contextHolder}
          </span>
          <br />
          <br />
          <Editor
            height={'80vh'}
            language={language}
            onMount={handleEditorDidMount}
          />
          <div className="language" style={{ marginTop: '10px' }}>
            <span>选择语言:</span>&ensp;
            <Select
              showSearch
              value={language}
              options={soptions}
              style={{ width: '100px' }}
              onSelect={(value) => {
                setLanguage(value)
              }}
              filterOption={(input, option) =>
                ((option?.label ?? '') as string)
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
            />
          </div>
        </div>
      </Content>
    </>
  )
}
